const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 8086;

// 中间件
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:3000'],
  credentials: true
}));
app.use(express.json());

// 日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('Headers:', req.headers);
  if (req.body && Object.keys(req.body).length > 0) {
    console.log('Body:', req.body);
  }
  next();
});

// 测试根路径
app.get('/', (req, res) => {
  res.json({
    message: 'HousingHub Test Backend Server',
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    port: PORT,
    timestamp: new Date().toISOString()
  });
});

// HousingHub API 路由
app.get('/housingHub', (req, res) => {
  res.json({
    message: 'HousingHub API Base',
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 发送验证码接口
app.post('/housingHub/user/send-code', (req, res) => {
  const { email } = req.body;
  
  console.log('🔔 收到发送验证码请求:', { email });
  
  if (!email) {
    return res.status(400).json({
      code: '400',
      message: '邮箱地址不能为空',
      data: null
    });
  }
  
  // 验证邮箱格式
  const emailRegex = /^[1-9]\d{4,10}@qq\.com$/;
  if (!emailRegex.test(email)) {
    return res.status(400).json({
      code: '400',
      message: '请输入正确的QQ邮箱格式',
      data: null
    });
  }
  
  // 模拟验证码发送
  const verificationCode = Math.floor(100000 + Math.random() * 900000);
  
  console.log(`✅ 验证码发送成功: ${email} -> ${verificationCode}`);
  
  res.json({
    code: '200',
    message: '验证码发送成功',
    data: {
      email: email,
      // 实际项目中不应该返回验证码，这里仅用于测试
      verificationCode: verificationCode,
      timestamp: new Date().toISOString()
    }
  });
});

// 用户注册接口
app.post('/housingHub/user/register', (req, res) => {
  const { username, email, password, confirmPassword, verificationCode } = req.body;
  
  console.log('🔔 收到用户注册请求:', { username, email, verificationCode });
  
  // 简单验证
  if (!username || !email || !password || !confirmPassword || !verificationCode) {
    return res.status(400).json({
      code: '400',
      message: '请填写完整的注册信息',
      data: null
    });
  }
  
  if (password !== confirmPassword) {
    return res.status(400).json({
      code: '400',
      message: '两次输入的密码不一致',
      data: null
    });
  }
  
  // 验证码验证（这里简单验证是否为6位数字）
  if (!/^\d{6}$/.test(verificationCode)) {
    return res.status(400).json({
      code: '400',
      message: '验证码格式不正确',
      data: null
    });
  }
  
  console.log(`✅ 用户注册成功: ${username} (${email})`);
  
  // 模拟注册成功
  res.json({
    code: '200',
    message: '注册成功',
    data: {
      userId: Math.floor(10000 + Math.random() * 90000),
      username: username,
      email: email,
      timestamp: new Date().toISOString()
    }
  });
});

// 用户登录接口
app.post('/housingHub/user/login', (req, res) => {
  const { email, password } = req.body;
  
  console.log('🔔 收到用户登录请求:', { email });
  
  if (!email || !password) {
    return res.status(400).json({
      code: '400',
      message: '邮箱和密码不能为空',
      data: null
    });
  }
  
  console.log(`✅ 用户登录成功: ${email}`);
  
  // 模拟登录成功
  res.json({
    code: '200',
    message: '登录成功',
    data: {
      token: 'test-token-' + Date.now(),
      userInfo: {
        userId: 12345,
        username: 'testuser',
        email: email
      },
      timestamp: new Date().toISOString()
    }
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('❌ 服务器错误:', err);
  res.status(500).json({
    code: '500',
    message: '服务器内部错误',
    data: null
  });
});

// 404处理
app.use('*', (req, res) => {
  console.log(`❓ 404 - 接口不存在: ${req.originalUrl}`);
  res.status(404).json({
    code: '404',
    message: '接口不存在',
    path: req.originalUrl,
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log('='.repeat(60));
  console.log(`🚀 HousingHub Test Backend Server 启动成功!`);
  console.log(`📍 服务地址: http://localhost:${PORT}`);
  console.log(`🔗 API基础路径: http://localhost:${PORT}/housingHub`);
  console.log(`📧 验证码接口: POST http://localhost:${PORT}/housingHub/user/send-code`);
  console.log(`👤 注册接口: POST http://localhost:${PORT}/housingHub/user/register`);
  console.log(`🔑 登录接口: POST http://localhost:${PORT}/housingHub/user/login`);
  console.log(`⏰ 启动时间: ${new Date().toISOString()}`);
  console.log('='.repeat(60));
  console.log('📝 等待API请求...\n');
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});
